import requests
import re
from bs4 import BeautifulSoup
from tornado.web import RequestHandler
import json

'''
    快手视频抓取
'''
class KuaishouHandler(RequestHandler):
    def get(self):
        url = self.request.protocol+"://"+self.request.host+self.request.uri
        self.render('kuaishou/index.html', nav_key=2, cur_url=url)

class ContentHandler(RequestHandler):
    def get(self):
        '''
        获取内容
        :param url:string
        :param key:string
        :return:
        '''
        key = self.get_argument('key')
        url = self.get_argument('url')
        data = {'code': 400}
        if key != 'kuaishou':
            data['msg'] = '输入快手网址不合法1'
            return self.finish(data)
        if self._is_kuaishou_url(url=url) == False:
            data['msg'] = '输入快手网址不合法2'
            return self.finish(data)

        response = requests.get(url)
        html_content = response.text
        data['msg'] = '没有抓取到内容，请拖到尾部，点击邮箱，帮忙报错!'
        if not html_content:
            data['code'] = 404
            return self.finish(data)
        cln = self._get_column(html_content)
        if not cln:
            return self.finish(data)

        data['code'] = 200
        data['msg'] = 'ok'
        data['data'] = cln
        return self.finish(data)


    def _is_kuaishou_url(self, url=''):
        '''
        判断你是否符合快手url
        :param url:string
        :return:bool
        '''
        patter_http = re.compile(r"^http://www.gifshow.com/s/.{3,}$").match(url)
        if patter_http == None:
            return False
        else:
            return True


    def _get_column(self, content=''):
        '''
        获取视频路径
        :param content:
        :return:
        '''

        soup = BeautifulSoup(content, "html.parser")
        pattern = re.compile(r"window.VUE_MODEL_INIT_STATE.profileGallery=(.*?);$", re.MULTILINE | re.DOTALL)
        script = soup.find("script", text=pattern)
        try:
            content = pattern.search(script.text).group(1)
            json_data = json.loads(content)
            video_url = json_data['work']['currentWork']['playUrl']
        except:
            video_url = '未知错误，请邮件联系管理员，并且发送复制的视频URL'
        return {'video_url': video_url}
